/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package core.game;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import org.apache.log4j.Logger;

/**
 *
 * @author Dung Pham
 */
public class GameThreadPool {

    private static final GameThreadPool instance;
    private final ThreadPoolExecutor threadPool;
    private boolean isShutdown;

    static {
        instance = new GameThreadPool();
    }

    private GameThreadPool() {
        this.isShutdown = false;
        this.threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
    }

    public static GameThreadPool getInstance() {
        return instance;
    }

    public void runTask(Runnable task) {
        this.threadPool.execute(task);
    }

    public void shutDown() {
        this.threadPool.shutdownNow();
        this.isShutdown = true;
    }

    /**
     * Override default function. Shutdown threadPool before finalizing.
     *
     * @throws Throwable An exception can be thrown.
     */
    @Override
    protected void finalize() throws Throwable {
        if (!this.isShutdown) {
            Logger.getLogger("").trace("Thread pool is shutting down.");
            this.threadPool.shutdown();
        }

        super.finalize();
    }
}
